package org.yelongframework.servlet.resource.response.support;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.yelongframework.commons.lang.StringUtil;
import org.yelongframework.core.resource.ResourceSupplier;
import org.yelongframework.core.resource.web.WebResourceSupplier;
import org.yelongframework.servlet.resource.response.ResourceResponseException;
import org.yelongframework.servlet.resource.response.ResourceResponseProperties;
import org.yelongframework.servlet.resource.response.responder.file.impl.html.HTMLFileResourceResponder;

/**
 * 默认实现
 * 
 * @since 1.0.0
 */
public class DefaultResourceResponseSupporter implements ResourceResponseSupporter {

	/** 资源供应商 */
	private ResourceSupplier resourceSupplier;

	/** WEB资源供应商 */
	private WebResourceSupplier webResourceSupplier;

	/** HTML文件资源响应器 */
	private HTMLFileResourceResponder htmlFileResourceResponder;

	/**
	 * @param resourceSupplier          资源供应商
	 * @param webResourceSupplier       WEB资源供应商
	 * @param htmlFileResourceResponder HTML文件资源响应器
	 */
	public DefaultResourceResponseSupporter(ResourceSupplier resourceSupplier, WebResourceSupplier webResourceSupplier,
			HTMLFileResourceResponder htmlFileResourceResponder) {
		this.resourceSupplier = Objects.requireNonNull(resourceSupplier);
		this.webResourceSupplier = Objects.requireNonNull(webResourceSupplier);
		this.htmlFileResourceResponder = Objects.requireNonNull(htmlFileResourceResponder);
	}

	@Override
	public void responseHtml(ResourceResponseProperties resourceResponseProperties, String resourcePackagePath,
			String resourceRelativePath) throws ResourceResponseException, IOException {
		resourceRelativePath = StringUtil.appendStartsSlash(resourceRelativePath);
		HttpServletRequest request = resourceResponseProperties.getRequest();
		InputStream inputStream = webResourceSupplier.getResourceAsStream(request.getServletContext(),
				WEB_INF + resourceRelativePath);
		if (null == inputStream) {
			String resourcePath = resourcePackagePath.replaceAll("[.]", "/");
			resourcePath = StringUtil.deleteEndsSlash(resourcePath);
			resourcePath += resourceRelativePath;
			inputStream = resourceSupplier.getResourceAsStream(resourcePath);
		}
		if (null == inputStream) {
			throw new ResourceResponseException("资源(" + resourceRelativePath + ")不存在");
		}
		htmlFileResourceResponder.response(inputStream, resourceResponseProperties);
	}

}
